package com.question.business.dept.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.question.business.dept.entity.DeptPost;
import com.question.business.dept.mapper.DeptPostMapper;
import com.question.business.dept.service.IDeptPostService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 部门岗位服务实现类
 *
 * @author star
 * @since 2023-09-14
 */
@Slf4j
@Service
public class DeptPostServiceImpl extends ServiceImpl<DeptPostMapper, DeptPost> implements IDeptPostService {

    /**
     * 部门岗位查询
     *
     * @param deptId 部门ID
     * @return List<String> 响应参数
     */
    @Override
    public List<String> queryPostByDeptId(String deptId) {
        return baseMapper.queryPostByDeptId(deptId);
    }

    /**
     * 岗位部门查询
     *
     * @param postId 岗位ID
     * @return List<String> 响应参数
     */
    @Override
    public List<String> queryDeptByPostId(String postId) {
        return baseMapper.queryDeptByPostId(postId);
    }

    /**
     * 部门岗位新增数据
     *
     * @param deptId  部门ID
     * @param postIds 岗位ID
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addDeptPost(@NotNull String deptId, List<String> postIds) {
        // 删除部门岗位
        baseMapper.deleteByDeptId(deptId);
        handleBatchAdd(Collections.singletonList(deptId), postIds);
    }

    /**
     * 处理批量保存
     *
     * @param deptIds 部门ID
     * @param postIds 岗位ID
     */
    private void handleBatchAdd(List<String> deptIds, List<String> postIds) {
        if (CollectionUtils.isNotEmpty(deptIds) && CollectionUtils.isNotEmpty(postIds)) {
            List<DeptPost> data = new ArrayList<>();
            for (String deptId : deptIds) {
                for (String postId : postIds) {
                    DeptPost entity = new DeptPost();
                    entity.setDeptId(deptId);
                    entity.setPostId(postId);
                    data.add(entity);
                }
            }
            super.saveBatch(data);
        }
    }

    /**
     * 岗位部门新增数据
     *
     * @param postId  岗位ID
     * @param deptIds 部门ID
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addPostDept(@NotNull String postId, List<String> deptIds) {
        // 删除岗位部门
        baseMapper.deleteByPostId(postId);
        handleBatchAdd(deptIds, Collections.singletonList(postId));
    }
}